﻿Public Class GeneralForm

    Dim wassaved As Boolean
    Dim wherewassaved As String

    Private Sub GeneralForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator"
        Try
            System.IO.Directory.Delete(path, True)
        Catch ex As Exception

        End Try
        ' Проверка запуска
        Dim file As String = Command$()
        If file = "" Then

        Else
            file = Replace(file, Chr(34), "")
            Dim fileext = System.IO.Path.GetExtension(file)
            If fileext = ".gcp" Then
                Try
                    System.IO.Directory.CreateDirectory(path)
                    System.IO.Directory.CreateDirectory(path + "\tmp")
                    Using zip1 As Ionic.Zip.ZipFile = Ionic.Zip.ZipFile.Read(file)
                        Dim y As Ionic.Zip.ZipEntry
                        For Each y In zip1
                            y.Extract(path + "\tmp\", Ionic.Zip.ExtractExistingFileAction.OverwriteSilently)
                        Next
                    End Using
                    ' Создание редактора гаджета(начало)
                    tabcontrol.TabPages.Clear()
                    Dim gadgetpage As New TabPage
                    gadgetpage.Text = "Гаджет"
                    Dim htmlbox As New FastColoredTextBoxNS.FastColoredTextBox
                    htmlbox.Language = FastColoredTextBoxNS.Language.HTML
                    htmlbox.Text = My.Settings.htmlsyntax
                    htmlbox.Dock = DockStyle.Fill
                    gadgetpage.Controls.Add(htmlbox)
                    gadgetpage.Name = "gadget.html"
                    tabcontrol.TabPages.Add(gadgetpage)
                    Dim htmlwriter As New System.IO.StreamWriter(path + "\gadget.html", True, System.Text.Encoding.GetEncoding(1251))
                    htmlwriter.Write(htmlbox.Text)
                    htmlwriter.Close()
                    tabcontrol.SelectedTab = gadgetpage

                    ' Создание редактора гаджета(конец)

                    browser.Checked = True
                    browsefiles.Visible = True
                    refreshfiles()
                    wassaved = True
                    wherewassaved = file
                    MsgBox("Проект загружен успешно!", 64, "Gadget Creator")
                Catch ex As Exception
                    MsgBox("Не удалось загрузить проект. Описание ошибки: " + ex.Message, 16, "Ошибка")
                End Try
            Else
                MsgBox("Файл, с расширением " + fileext + ", не является проектом Gadget Creator.", 48, "Открытие файла...")
            End If
        End If

    End Sub
    Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click, newmini.Click
        If MsgBox("Все несохранённые данные будут стёрты. Продолжить?", 36, "Gadget Creator Beta Preview 2") = MsgBoxResult.Yes Then

            tabcontrol.TabPages.Clear()
            Dim gadgetpage As New TabPage
            ' Удаление временной директории
            Try
                Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator\tmp"
                If System.IO.Directory.Exists(path) = True Then
                    System.IO.Directory.Delete(path, True)
                    System.IO.Directory.CreateDirectory(path)
                Else
                    System.IO.Directory.CreateDirectory(path)
                End If
                Dim writer As New System.IO.StreamWriter(path + "\gadget.xml", True, System.Text.Encoding.UTF8)
                writer.Write(My.Resources.xmldefault)
                writer.Close()
                ' Создание редактора гаджета(начало)

                gadgetpage.Text = "Гаджет"
                Dim htmlbox As New FastColoredTextBoxNS.FastColoredTextBox
                htmlbox.Language = FastColoredTextBoxNS.Language.HTML
                htmlbox.Text = My.Settings.htmlsyntax
                htmlbox.Dock = DockStyle.Fill
                gadgetpage.Controls.Add(htmlbox)
                gadgetpage.Name = "gadget.html"
                tabcontrol.TabPages.Add(gadgetpage)
                Dim htmlwriter As New System.IO.StreamWriter(path + "\gadget.html", True, System.Text.Encoding.GetEncoding(1251))
                htmlwriter.Write(htmlbox.Text)
                htmlwriter.Close()

                ' Создание редактора гаджета(конец)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try

            browser.Checked = True
            browsefiles.Visible = True
            refreshfiles()

            tabcontrol.SelectedTab = gadgetpage
            wassaved = False
            GadgetSetForm.Show()
        End If
        wassaved = False
        wherewassaved = ""
    End Sub
    Private Sub СвойстваГаджетаToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles СвойстваГаджетаToolStripMenuItem.Click
        GadgetSetForm.Show()
    End Sub

    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click, openmini.Click
        If MsgBox("Все несохранённые данные будут потеряны! Продолжить?", 36, "Открыть проект") = MsgBoxResult.Yes Then
            Dim ofd As New OpenFileDialog
            ofd.Filter = "Проекты Gadget Creator|*.gcp"
            ofd.Title = "Открыть проект Gadget Creator"
            If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
                Dim fileext As String = System.IO.Path.GetExtension(ofd.FileName)
                If fileext = ".gcp" Then
                    Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator\tmp"
                    tabcontrol.TabPages.Clear()
                    Try
                        System.IO.Directory.Delete(path + "\", True)
                        System.IO.Directory.CreateDirectory(path + "\")
                    Catch ex As Exception
                        MsgBox(ex.Message, 16, "Gadget Creator")
                    End Try
                    Using zip1 As Ionic.Zip.ZipFile = Ionic.Zip.ZipFile.Read(ofd.FileName)
                        Dim y As Ionic.Zip.ZipEntry
                        For Each y In zip1
                            y.Extract(path, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently)
                        Next
                    End Using
                    Try
                        If System.IO.File.Exists(path + "\gadget.xml") = False Then
                            MsgBox("Проект повреждён и не может быть открыт!", 64, "Открытие проекта...")
                            Exit Sub
                        Else
                            If System.IO.File.Exists(path + "\gadget.html") = False Then
                                Dim creategadgetfile As New System.IO.StreamWriter(path)
                                creategadgetfile.Write(My.Settings.htmlsyntax)
                                creategadgetfile.Close()
                                Dim gadgetpage As New TabPage
                                gadgetpage.Name = "gadget.html"
                                gadgetpage.Text = "Гаджет"
                                Dim htmlbox As New FastColoredTextBoxNS.FastColoredTextBox
                                htmlbox.Language = FastColoredTextBoxNS.Language.HTML
                                htmlbox.Text = My.Settings.htmlsyntax
                                htmlbox.Dock = DockStyle.Fill
                                gadgetpage.Controls.Add(htmlbox)
                                tabcontrol.TabPages.Add(gadgetpage)
                            Else
                                Dim opengadgetfile As New System.IO.StreamReader(path + "\gadget.html", System.Text.Encoding.GetEncoding(1251))
                                Dim gadgetpage As New TabPage
                                gadgetpage.Name = "gadget.html"
                                gadgetpage.Text = "Гаджет"
                                Dim htmlbox As New FastColoredTextBoxNS.FastColoredTextBox
                                htmlbox.Language = FastColoredTextBoxNS.Language.HTML
                                htmlbox.Text = opengadgetfile.ReadToEnd()
                                opengadgetfile.Close()
                                htmlbox.Dock = DockStyle.Fill
                                gadgetpage.Controls.Add(htmlbox)
                                tabcontrol.TabPages.Add(gadgetpage)
                                tabcontrol.SelectedTab = gadgetpage
                            End If
                            MsgBox("Проект загружен успешно!", 64, "Gadget Creator")
                        End If
                    Catch ex As Exception
                        MsgBox(ex.Message, 16, "Ошибка")
                    End Try

                Else

                    MsgBox("Файл, с расширением " + fileext + ", не является проектом Gadget Creator")

                End If

            End If
            wassaved = True
            wherewassaved = ofd.FileName
            browser.Checked = True
            browsefiles.Visible = True
            refreshfiles()
        Else

        End If
    End Sub

    Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click, savemini.Click
        If wassaved = True Then
            Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator\tmp\"
            saveall()
            Try
                Using zip As Ionic.Zip.ZipFile = New Ionic.Zip.ZipFile()
                    Dim filenames As String() = System.IO.Directory.GetFiles(path)
                    zip.AddFiles(filenames, "")
                    zip.Save(wherewassaved)
                End Using
                MsgBox("Проект сохранён успешно!", 64, "Gadget Creator")
            Catch ex As Exception
                MsgBox("Не удалось сохранить проект в единый файл! Описание ошибки: " + ex.Message, 16, "Ошибка")
            End Try
        Else
            Dim sfd As New SaveFileDialog
            sfd.Filter = "Проекты Gadget Creator|*.gcp"
            sfd.Title = "Сохранить проект"
            If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
                saveall()
                Try
                    Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator\tmp\"
                    Using zip As Ionic.Zip.ZipFile = New Ionic.Zip.ZipFile()
                        Dim filenames As String() = System.IO.Directory.GetFiles(path)
                        zip.AddFiles(filenames, "")
                        zip.Save(sfd.FileName)
                    End Using
                    wassaved = True
                    wherewassaved = sfd.FileName
                    MsgBox("Проект сохранён успешно!", 64, "Gadget Creator")
                Catch ex As Exception
                    MsgBox("Не удалось сохранить проект в единый файл! Описание ошибки: " + ex.Message, 16, "Ошибка")
                End Try
            End If
        End If
    End Sub

    Public Sub saveall()
        Try
            Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator\tmp"
            tabcontrol.SelectedIndex = 0
            For Each TabPage In tabcontrol.TabPages
                Dim writer As New System.IO.StreamWriter(path + "\" + tabcontrol.SelectedTab.Name, False, System.Text.Encoding.GetEncoding(1251))
                writer.Write(CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).Text)
                writer.Close()
                tabcontrol.SelectedIndex = +1
            Next
        Catch ex As Exception
            MsgBox("Не удалось сохранить проект(отдельный документ). Описание ошибки:" + ex.Message, 16, "Оишбка")
        End Try
    End Sub

    Private Sub UndoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UndoToolStripMenuItem.Click
        CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).Undo()
    End Sub

    Private Sub RedoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RedoToolStripMenuItem.Click
        CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).Redo()
    End Sub

    Private Sub cut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cut.Click
        CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).Cut()
    End Sub

    Private Sub copy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles copy.Click
        CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).Copy()
    End Sub

    Private Sub paste_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles paste.Click
        CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).Paste()
    End Sub

    Private Sub selectall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles selectall.Click
        CType(tabcontrol.SelectedTab.Controls(0), FastColoredTextBoxNS.FastColoredTextBox).SelectAll()
    End Sub

    Private Sub КомпилироватьToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles КомпилироватьToolStripMenuItem.Click

        '  Начать компиляцию
        Dim sfd As New SaveFileDialog
        sfd.Filter = "Гаджет Windows Sidebar|*.gadget"
        If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator\tmp\"
            Using zip As Ionic.Zip.ZipFile = New Ionic.Zip.ZipFile()
                Dim filenames As String() = System.IO.Directory.GetFiles(path)
                zip.AddFiles(filenames, "")
                zip.Save(sfd.FileName)
            End Using
        End If
    End Sub
    Public Sub refreshfiles()
        Try
            ListView1.Items.Clear()
            Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator\tmp"
            Dim folderInfo As New IO.DirectoryInfo(path)
            Dim arrFilesInFolder() As IO.FileInfo
            Dim fileInFolder As IO.FileInfo
            arrFilesInFolder = folderInfo.GetFiles("*.html")
            For Each fileInFolder In arrFilesInFolder
                ListView1.Items.Add(fileInFolder.Name).StateImageIndex = 0
            Next
            arrFilesInFolder = folderInfo.GetFiles("*.xml")
            For Each fileInFolder In arrFilesInFolder
                ListView1.Items.Add(fileInFolder.Name).StateImageIndex = 1
            Next
            arrFilesInFolder = folderInfo.GetFiles("*.js")
            For Each fileInFolder In arrFilesInFolder
                ListView1.Items.Add(fileInFolder.Name).StateImageIndex = 2
            Next
            arrFilesInFolder = folderInfo.GetFiles("*.txt")
            For Each fileInFolder In arrFilesInFolder
                ListView1.Items.Add(fileInFolder.Name).StateImageIndex = 3
            Next
            arrFilesInFolder = folderInfo.GetFiles("*.css")
            For Each fileInFolder In arrFilesInFolder
                ListView1.Items.Add(fileInFolder.Name).StateImageIndex = 4
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged
        tabcontrol.SelectedIndex = 0
        deletefile.Enabled = True
        Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator\tmp"
        If ListView1.SelectedItems.Count > 0 Then
            Dim type = ListView1.FocusedItem.Text
            If type = "gadget.xml" Then
                MsgBox("В режиме 'Простой' нельзя редактировать файл gadget.xml в редакторе", 64, "Редактирование")
                GadgetSetForm.Show()
                deletefile.Enabled = False
            End If
            If type.EndsWith(".html") = True Then
                If tabcontrol.TabPages.ContainsKey(type) = True Then
                    tabcontrol.SelectTab(type)
                Else
                    Dim editor As New TabPage
                    editor.Text = ListView1.FocusedItem.Text
                    editor.Name = ListView1.FocusedItem.Text
                    Dim htmlbox As New FastColoredTextBoxNS.FastColoredTextBox
                    htmlbox.Language = FastColoredTextBoxNS.Language.HTML
                    Dim reader As New System.IO.StreamReader(path + "\" + ListView1.FocusedItem.Text, System.Text.Encoding.GetEncoding(1251))
                    htmlbox.Text = reader.ReadToEnd
                    reader.Close()
                    htmlbox.Dock = DockStyle.Fill
                    editor.Controls.Add(htmlbox)
                    tabcontrol.TabPages.Add(editor)
                    tabcontrol.SelectedTab = editor
                End If
            End If
            If type.EndsWith(".js") = True Then
                If tabcontrol.TabPages.ContainsKey(type) = True Then
                    tabcontrol.SelectTab(type)
                Else
                    Dim editor As New TabPage
                    editor.Text = ListView1.FocusedItem.Text
                    editor.Name = ListView1.FocusedItem.Text
                    Dim jsbox As New FastColoredTextBoxNS.FastColoredTextBox
                    jsbox.Language = FastColoredTextBoxNS.Language.JS
                    Dim reader As New System.IO.StreamReader(path + "\" + ListView1.FocusedItem.Text, System.Text.Encoding.GetEncoding(1251))
                    jsbox.Text = reader.ReadToEnd
                    reader.Close()
                    jsbox.Dock = DockStyle.Fill
                    editor.Controls.Add(jsbox)
                    tabcontrol.TabPages.Add(editor)
                    tabcontrol.SelectedTab = editor
                End If
            End If
            If type.EndsWith(".css") = True Then
                If tabcontrol.TabPages.ContainsKey(type) = True Then
                    tabcontrol.SelectTab(type)
                Else
                    Dim editor As New TabPage
                    editor.Text = ListView1.FocusedItem.Text
                    editor.Name = ListView1.FocusedItem.Text
                    Dim cssbox As New FastColoredTextBoxNS.FastColoredTextBox
                    Dim reader As New System.IO.StreamReader(path + "\" + ListView1.FocusedItem.Text, System.Text.Encoding.GetEncoding(1251))
                    cssbox.Text = reader.ReadToEnd
                    reader.Close()
                    cssbox.Dock = DockStyle.Fill
                    editor.Controls.Add(cssbox)
                    tabcontrol.TabPages.Add(editor)
                    tabcontrol.SelectedTab = editor
                End If
            End If
            If type.EndsWith(".txt") = True Then
                If tabcontrol.TabPages.ContainsKey(type) = True Then
                    tabcontrol.SelectTab(type)
                Else
                    Dim editor As New TabPage
                    editor.Text = ListView1.FocusedItem.Text
                    editor.Name = ListView1.FocusedItem.Text
                    Dim txtbox As New FastColoredTextBoxNS.FastColoredTextBox
                    txtbox.Language = FastColoredTextBoxNS.Language.Custom
                    Dim reader As New System.IO.StreamReader(path + "\" + ListView1.FocusedItem.Text, System.Text.Encoding.GetEncoding(1251))
                    txtbox.Text = reader.ReadToEnd
                    reader.Close()
                    txtbox.Dock = DockStyle.Fill
                    editor.Controls.Add(txtbox)
                    tabcontrol.TabPages.Add(editor)
                    tabcontrol.SelectedTab = editor
                End If
            End If
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        CreateFile.Show()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletefile.Click
        If ListView1.SelectedItems.Count > 0 Then
            If tabcontrol.TabPages.ContainsKey(ListView1.FocusedItem.Text) = True Then
                tabcontrol.SelectTab(ListView1.FocusedItem.Text)
                tabcontrol.TabPages.Remove(tabcontrol.SelectedTab)
                Try
                    Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\Gadget Creator\tmp\"
                    IO.File.Delete(path + ListView1.FocusedItem.Text)
                    refreshfiles()
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try
            Else
            End If
        Else
            MsgBox("По непонятным причинам невозможно удалить файл...", 16, "Ошибка")
        End If
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Application.Exit()
    End Sub

    Private Sub ОбозревательФайловToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browser.Click
        If browser.Checked = True Then
            browser.Checked = False
            browsefiles.Visible = False
            refreshfiles()
        Else
            browser.Checked = True
            browsefiles.Visible = True
            refreshfiles()
        End If
    End Sub

End Class
